package com.cloud.common.config;

import com.cloud.common.support.DefaultScheduledThreadPoolExecutor;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.*;

/**
 * 线程池配置类
 *
 * @author fengwenjin
 */
@Configuration
public class ThreadPoolConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler scheduler = new DefaultThreadPoolTaskScheduler();
        scheduler.setPoolSize(Runtime.getRuntime().availableProcessors());
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.setAwaitTerminationSeconds(600);
        scheduler.setThreadNamePrefix("scheduling-");
        scheduler.setDaemon(true);
        scheduler.initialize();
        taskRegistrar.setTaskScheduler(scheduler);
    }

    static class DefaultThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {

        private ScheduledExecutorService scheduledExecutor;

        @Override
        protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
            scheduledExecutor = new DefaultScheduledThreadPoolExecutor(this.getPoolSize(), this, new ThreadPoolExecutor.CallerRunsPolicy());
            return scheduledExecutor;
        }

        @Override
        public ScheduledExecutorService getScheduledExecutor() {
            return scheduledExecutor;
        }
    }

}

